package eu.news.servlet.admin.news;

import java.io.IOException;
import java.net.URLDecoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import eu.jk.base.security.AuthFilter;
import eu.news.data.dao.DAOFactory;
import eu.news.data.dao.NewsDAO;
import eu.news.data.dao.SpecialDAO;
import eu.news.data.pojo.News;
import eu.news.data.pojo.Operator;
import eu.news.data.pojo.Special;
import eu.news.kits.SecurityManager;

/**
 * 返回添加新闻界面
 */
public class EditNews extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EditNews() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String uri=request.getRequestURI();
		String[] fields=uri.split("/");
		String specialName=URLDecoder.decode(fields[fields.length-2],"UTF-8");
		String type=URLDecoder.decode(fields[fields.length-1],"UTF-8");
		Operator operator=SecurityManager.getOperator(request);
		Special special=null;
		/*
		 编辑旧新闻 
		 */
		if(AuthFilter.isDigit(type)){
			NewsDAO nDao = DAOFactory.getNewsDAO();
			News news=nDao.getById(Integer.parseInt(type));
			if(news==null){
				response.sendError(404);
				return;
			}
			request.setAttribute("news", news);
			if(news.getType()==News.TYPE.GALLERY)
				type="picture";
			special=news.getSort().getSpecial();
		}else{
			SpecialDAO spDao=DAOFactory.getSpecialDAO();
			special=spDao.getByName(specialName);
		}
		if(!auth(special,operator)){
			response.sendError(404);
			return;
		}
		request.setAttribute("op", operator);
		request.setAttribute("sp", special);
		if("picture".equals(type)){
			request.getRequestDispatcher("/admin/face/news/pic_news.jsp").forward(request, response);
		}else{
			request.getRequestDispatcher("/admin/face/news/news.jsp").forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	public static boolean auth(Special special,Operator op){
		if(op.getSpecials().contains(special))
			return true;
		return false;
	}
}
